
import Taro, { getStorageSync, addInterceptor, request } from '@tarojs/taro'

import interceptors from './interceptors'
import getBaseUrl from './baseUrl'

interceptors.forEach(i => addInterceptor(i))
class fetch {
  baseOptions (params, method = 'GET') {
    let { url, data } = params
    const BASE_URL = getBaseUrl(url)
    const contentType = 'application/json'
    const option = {
      url: `${BASE_URL}${url}`,
      data,
      method,
      header: {
        'content-type': contentType,
        Authorization: getStorageSync('Authorization'),
      },

    }
    return request(option).then(res => {
      if (res.code == 0) {
        console.group(`请求接口 ${BASE_URL}${url}`);
        console.log(res);
        console.groupEnd();
        if (res.code !== 0) {
          Taro.showToast({
            title: `${res.message}~` || res.code,
            icon: 'none',
            mask: true,
          });
        }
        return res;
      } else {
        throw new Error(`网络请求错误，状态码${res.code}`);
      }
    }
    );
  }

  get (url, data) {
    let option = { url, data }
    return this.baseOptions(option)
  }
  post (url, data, contentType) {
    let params = { url, data, contentType }
    return this.baseOptions(params, 'POST')
  }
  put (url, data) {
    let option = { url, data }
    return this.baseOptions(option, 'PUT')
  }
  delete (url, data) {
    let option = { url, data }
    return this.baseOptions(option, 'DELETE')
  }
}

export default new fetch()
